import { Form, Input, Button, message } from 'antd';
import { updateUserInfo } from '@/services/api/user/user';
import useBack from '@/views/hooks/useBack';
import { useNavigate } from 'react-router-dom';
import getOss from '../hooks/useOss';
import imgSrc from '@/assets/images/login_bg.jpg';
export default function UpdateUserInfo() {
  const [headPicUrl, setHeadPicUrl] = useState(imgSrc);
  const [currentFile, setCurrentFile] = useState<Record<any, any>>();

  useEffect(() => {
    const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}');
    setHeadPicUrl(userInfo.headPic);
  }, []);
  const { back } = useBack();
  const navigage = useNavigate();
  function createInput() {
    const inp = document.createElement('input');
    inp.type = 'file';
    inp.style.display = 'none';
    document.body.appendChild(inp);
    return inp;
  }
  function createUrl(file: any) {
    return URL.createObjectURL(file);
  }
  const uploadImg = () => {
    const inp = createInput();
    inp.value = '';
    inp.click();
    inp.onchange = async () => {
      const file = inp.files?.[0];

      setCurrentFile(file);

      setHeadPicUrl(createUrl(file));
    };
  };
  const onFinish = async (values: any) => {
    const client = await getOss();
    const url = await client.put(
      `${import.meta.env.VITE_OSS_DIR}${currentFile?.name}`,
      currentFile
    );
    values.headPic = url.url;
    const res = await updateUserInfo(values);
    if (res.code === 200) {
      message.success('修改成功');
      back();
    }
  };
  return (
    <div className=" relative w-screen h-screen bg-[url('src/assets/images/login_bg.jpg')]  ">
      <div className=" w-1/3 bg-slate-50 p-4 absolute top-[40%] left-[50%] translate-x-[-50%] translate-y-[-50%]">
        <h1 className=" flex justify-center my-3">会议室预定系统</h1>
        <Form
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          onFinish={onFinish}
          colon={false}
          autoComplete="off"
        >
          <Form.Item label="头像" name="headPic">
            <img onClick={uploadImg} className=" w-10 h-10" src={headPicUrl} alt="" />
          </Form.Item>
          <Form.Item label="邮箱" name="email">
            <Input />
          </Form.Item>
          <Form.Item label="昵称" name="nickName">
            <Input />
          </Form.Item>
          <Form.Item labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
            <div className=" ml-7 cursor-pointer" onClick={() => navigage(-1)}>
              返回
            </div>
          </Form.Item>
          <Form.Item labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
            <div className=" flex justify-center ">
              <Button className="w-full" type="primary" htmlType="submit">
                修改信息
              </Button>
            </div>
          </Form.Item>
        </Form>
      </div>
    </div>
  );
}
